<template>
  <el-container>
    <el-header>
      <div>
        <el-form :model="state.queryParams" ref="queryForm" :inline="true">
          <el-form-item label="文件名称" prop="fileName">
            <el-input v-model="state.queryParams.fileName" placeholder="文件名称" clearable />
          </el-form-item>
          <el-form-item label="文件编号" prop="fileNo">
            <el-input v-model="state.queryParams.fileNo" placeholder="文件编号" clearable />
          </el-form-item>
          <el-form-item label="开始时间" prop="name">
            <el-date-picker v-model="state.queryParams.startTime" type="datetime" placeholder="开始时间" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item label="结束时间" prop="code">
            <el-date-picker v-model="state.queryParams.endTime" type="datetime" placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery"> 查询 </el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery"> 重置 </el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>
    </el-header>
    <el-header>
      <div class="left-panel">
        <el-button type="primary" icon="el-icon-plus" @click="openUploadDialog"> 上传 </el-button>
      </div>
    </el-header>
    <el-main class="nopadding">
      <scTable ref="table" tableName="listCustomColumn" :apiObj="apiObj" :params="state.queryParams" row-key="uploadFilesId" stripe>
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="originName" label="名称" min-width="150" header-align="center" show-overflow-tooltip />
        <el-table-column prop="suffix" label="后缀" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag round>{{ scope.row.suffix }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sizeFormat" label="大小" align="center" show-overflow-tooltip />
        <el-table-column prop="path" label="预览" align="center">
          <template #default="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="getFileUrl(scope.row)"
              v-show="isImage(scope.row.suffix)"
              alt="无法预览"
              :lazy="true"
              :hide-on-click-modal="true"
              :preview-src-list="[getFileUrl(scope.row)]"
              :initial-index="0"
              fit="scale-down"
              preview-teleported
            >
              <template #error> </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="storageKey" label="存储位置" align="center" show-overflow-tooltip />
        <el-table-column prop="fileNo" label="存储标识" align="center" show-overflow-tooltip />
        <el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-popover placement="bottom" width="280" trigger="hover">
              <template #reference>
                <el-text type="primary">
                  <el-icon type="primary" style="vertical-align: middle"><el-icon-info-filled /></el-icon>详情
                </el-text>
              </template>
              <el-descriptions direction="vertical" :column="2" border>
                <el-descriptions-item width="140">
                  <template #label>
                    <el-text>
                      <el-icon style="vertical-align: middle"><el-icon-user /></el-icon>创建者
                    </el-text>
                  </template>
                  <el-tag>{{ scope.row.creatorName ?? '无' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <el-text>
                      <el-icon style="vertical-align: middle"><el-icon-calendar /></el-icon>创建时间
                    </el-text>
                  </template>
                  <el-tag>{{ scope.row.createdTime ?? '无' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <el-text>
                      <el-icon style="vertical-align: middle"><el-icon-User /></el-icon>修改者
                    </el-text>
                  </template>
                  <el-tag>{{ scope.row.lastModifierName ?? '无' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <el-text>
                      <el-icon style="vertical-align: middle"><el-icon-calendar /></el-icon>修改时间
                    </el-text>
                  </template>
                  <el-tag>{{ scope.row.lastModifiedTime ?? '无' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <el-text>
                      <el-icon style="vertical-align: middle"><el-icon-tickets /></el-icon>备注
                    </el-text>
                  </template>
                  {{ scope.row.remark }}
                </el-descriptions-item>
              </el-descriptions>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-button icon="el-icon-view" size="small" text type="primary" @click="openFilePreviewDialog(scope.row)" v-show="isImage(scope.row.suffix)">
              预览
            </el-button>
            <el-button icon="el-icon-download" size="small" text type="primary" @click="downloadFile(scope.row)"> 下载 </el-button>
            <el-button icon="el-icon-delete" size="small" text type="danger" @click="delFile(scope.row)"> 删除 </el-button>
            <el-button icon="el-icon-edit" size="small" text type="primary" @click="openEditSysFile(scope.row)"> 编辑 </el-button>
          </template>
        </el-table-column>
      </scTable>
    </el-main>
  </el-container>

  <el-dialog title="上传" v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
    <template #header>
      <div>
        <el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
          <el-icon-upload-filled />
        </el-icon>
        <span> 上传文件 </span>
      </div>
    </template>
    <div>
      <el-upload
        ref="uploadRef"
        drag
        :auto-upload="false"
        :limit="1"
        :file-list="state.fileList"
        action=""
        :on-change="handleChange"
        accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx"
      >
        <el-icon class="el-icon--upload">
          <el-icon-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
        </template>
      </el-upload>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogUploadVisible = false">取消</el-button>
        <el-button type="primary" @click="uploadFile">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-drawer :title="state.fileName" v-model="state.dialogDocxVisible" size="50%" destroy-on-close>
    <vue-office-docx :src="state.docxUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler" />
  </el-drawer>
  <el-drawer :title="state.fileName" v-model="state.dialogXlsxVisible" size="50%" destroy-on-close>
    <vue-office-excel :src="state.excelUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler"
  /></el-drawer>
  <el-drawer :title="state.fileName" v-model="state.dialogPdfVisible" size="50%" destroy-on-close>
    <vue-office-pdf :src="state.pdfUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler"
  /></el-drawer>
  <el-image-viewer v-if="state.showViewer" :url-list="state.previewList" @close="state.showViewer = false"></el-image-viewer>
  <!-- <EditSysFile
			ref="editSysFileRef"
			title="编辑文件"
			@handleQuery="handleQuery"
		/> -->
</template>

<script>
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';
import { downloadByUrlFetch } from '@/utils/download';

export default {
  name: 'files',
  components: {
    VueOfficeDocx,
    VueOfficeExcel,
    VueOfficePdf,
  },
  data() {
    return {
      apiObj: this.$API.upload.page,
      state: {
        fileData: [],
        loading: false,
        queryParams: {
          fileName: '',
          startTime: '',
          endTime: '',
        },
        tableParams: {
          page: 1,
          pageSize: 10,
          total: 0,
        },
        dialogUploadVisible: false,
        fileList: [],
        fileName: '',
        showViewer: false,
        dialogDocxVisible: false,
        dialogXlsxVisible: false,
        dialogPdfVisible: false,
        docxUrl: '',
        excelUrl: '',
        pdfUrl: '',
        previewList: [],
      },
    };
  },
  mounted() {},
  beforeUnmount() {},
  methods: {
    async handleQuery() {
      this.$refs.table.refresh();
    },
    async resetQuery() {
      this.state.queryParams.fileName = undefined;
      this.state.queryParams.startTime = undefined;
      this.state.queryParams.endTime = undefined;
      this.handleQuery();
    },
    openUploadDialog() {
      this.state.fileList = [];
      this.state.dialogUploadVisible = true;
    },
    handleChange(file, fileList) {
      this.state.fileList = fileList;
    },

    async uploadFile() {
      if (this.state.fileList.length < 1) return;
      let response = await this.$API.upload.upload2.post(this.state.fileList[0].raw);
      console.log(response);
      if (response.code != 200) {
        this.$message.error(response.message);
        return;
      }
      this.handleQuery();
      this.$message.success('上传成功');
      this.state.dialogUploadVisible = false;
    },
    async downloadFile(row) {
      var fileUrl = this.getFileUrl(row);
      downloadByUrlFetch({ url: fileUrl });
    },
    delFile(row) {
      this.$confirm(`确定删除文件：【${row.originName}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let response = await this.$API.upload.remove.post(row.uploadFilesId);
          if (response.code == 200) {
            // await getAPI(SysFileApi).apiSysFileDeletePost({ id: row.id });
            this.handleQuery();
            this.$message.success('删除成功');
          }
        })
        .catch(() => {});
    },
    isImage(suffix) {
      return ['.jpg', '.png', '.jpeg', '.bmp'].findIndex(e => e == suffix) > -1;
    },
    async openFilePreviewDialog(row) {
      if (row.suffix == '.pdf') {
        this.state.fileName = `【${row.fileNo}${row.suffix}】`;
        this.state.pdfUrl = this.getFileUrl(row);
        this.state.dialogPdfVisible = true;
      } else if (row.suffix == '.docx') {
        this.state.fileName = `【${row.fileNo}${row.suffix}】`;
        this.state.docxUrl = this.getFileUrl(row);
        this.state.dialogDocxVisible = true;
      } else if (row.suffix == '.xlsx') {
        this.state.fileName = `【${row.fileNo}${row.suffix}】`;
        this.state.excelUrl = this.getFileUrl(row);
        this.state.dialogXlsxVisible = true;
      } else if (['.jpg', '.png', '.jpeg', '.bmp'].findIndex(e => e == row.suffix) > -1) {
        this.state.previewList = [this.getFileUrl(row)];
        this.state.showViewer = true;
      } else {
        this.$message.error('此文件格式不支持预览');
      }
    },
    getFileUrl(row) {
      return row.url;
    },
    openEditSysFile(row) {
      this.$refs.editSysFileRef.open(row);
    },
    renderedHandler() {},
    errorHandler() {},
  },
};
</script>
